#include <stdio.h>
#include <stdlib.h>

static FILE *file_capacity = NULL, *file_voltage = NULL;
static FILE *file_temp1 = NULL, *file_temp2 = NULL;

int init_system_readings_file() {
    int result = EXIT_SUCCESS;
    // 打开电池容量文件
    file_capacity = fopen("/sys/class/power_supply/bms/capacity", "r");
    if (file_capacity == NULL) {
        perror("Error opening capacity file");
        result = EXIT_FAILURE;
    }

    // 打开电池电压文件
    file_voltage = fopen("/sys/class/power_supply/bms/voltage_now", "r");
    if (file_voltage == NULL) {
        perror("Error opening voltage file");
        result = EXIT_FAILURE;
    }

    file_temp1 = fopen("/sys/class/hwmon/hwmon0/temp1_input", "r");
    if (file_temp1 == NULL) {
        perror("Error opening temp1 file");
        result = EXIT_FAILURE;
    }

    file_temp2 = fopen("/sys/class/hwmon/hwmon1/temp1_input", "r");
    if (file_temp2 == NULL) {
        perror("Error opening temp2 file");
        result = EXIT_FAILURE;
    }
    return result;
}

int read_battery_capacity() {
    char buffer_capacity[64];
    if (file_capacity) {
        rewind(file_capacity);
        if (fgets(buffer_capacity, sizeof(buffer_capacity), file_capacity) == NULL) {
            perror("Error reading capacity file");
            return -1;
        }
        return atoi(buffer_capacity);
    } else {
        return -1;
    }
}

int read_battery_voltage() {
    char buffer_voltage[64];
    if (file_voltage) {
        rewind(file_voltage);
        if (fgets(buffer_voltage, sizeof(buffer_voltage), file_voltage) == NULL) {
            perror("Error reading voltage file");
            return -1;
        }
        return atoi(buffer_voltage);
    } else {
        return -1;
    }
}

int read_system_temp1() {
    char buffer_temp[64];
    if (file_temp1) {
        rewind(file_temp1);
        if (fgets(buffer_temp, sizeof(buffer_temp), file_temp1) == NULL) {
            perror("Error reading temp1 file");
            return -1;
        }
        return atoi(buffer_temp);
    } else {
        return -1;
    }
}

int read_system_temp2() {
    char buffer_temp[64];
    if (file_temp2) {
        rewind(file_temp2);
        if (fgets(buffer_temp, sizeof(buffer_temp), file_temp2) == NULL) {
            perror("Error reading temp2 file");
            return -1;
        }
        return atoi(buffer_temp);
    } else {
        return -1;
    }
}

void close_system_readings_file() {
    if (file_capacity)
        fclose(file_capacity);
    if (file_voltage)
        fclose(file_voltage);
    if (file_temp1)
        fclose(file_temp1);
    if (file_temp2)
        fclose(file_temp2);
}
